<template>
  <Dialog
    v-model="show"
    :title="props.data?.id ? $t('tenantAddress.编辑地址') : $t('tenantAddress.新增地址')"
    width="700px"
    @close="close"
    @confirm="handleSubmit"
  >
    <LangTabs v-model="lang" />
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="160px">
      <el-form-item :label="$t('tenantAddress.收货人')" :prop="'name' + lang">
        <el-input
          v-model="formData['name' + lang]"
          :placeholder="$t('tenantAddress.请输入收货人')"
        />
      </el-form-item>
      <el-form-item :label="$t('tenantAddress.联系电话')" :prop="'phone'">
        <el-input v-model="formData.phone" :placeholder="$t('tenantAddress.请输入联系电话')" />
      </el-form-item>
      <el-form-item :label="$t('tenantAddress.选择省市区')" :prop="'region'">
        <el-cascader v-model="formData.region" :props="cascaderProps" style="width: 100%;" />
      </el-form-item>
      <el-form-item :label="$t('tenantAddress.详细地址')" :prop="'address' + lang">
        <el-input
          v-model="formData['address' + lang]"
          :placeholder="$t('tenantAddress.请输入详细地址')"
          type="textarea"
          :rows="4"
        />
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script setup>
import { ref, watch, reactive } from "vue";
import Dialog from "@/components/dialog.vue";
import LangTabs from "@/components/LangTabs.vue";
import { useI18n } from "vue-i18n";
import i18n from "@/i18n";
import { ElMessage } from "element-plus";
import Api from "@/config/api/api";

const { locale, t } = useI18n();

const lang = ref(locale.value);
const langs = reactive(Object.keys(i18n.global.messages.value));
const show = defineModel();
const emit = defineEmits(["success"]);

const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
});

const cascaderProps = ref({
  lazy: true,
  label: "name" + locale.value,
  value: "id",
  lazyLoad(node, resolve) {
    const { level } = node;
    Api.getRegion({
      parentId: node.value || 0,
    }).then((res) => {
      if (level == 2) {
        res.data?.forEach((item) => {
          item.children = [];
          item.leaf = true;
        });
      }
      resolve(res.data || []);
    });
  },
});

// 表单数据
const formData = ref({
  region: [],
});
// 表单校验规则
const rules = ref({
  phone: [{ required: true, message: t('tenantAddress.请输入联系电话'), trigger: "blur" }],
  region: [{ required: true, message: t('tenantAddress.请选择省市区'), trigger: "blur" }],
});

langs.forEach((item) => {
  formData.value["name" + item] = "";
  formData.value["address" + item] = "";
  rules.value["name" + item] = [
    { required: true, message: t('tenantAddress.请输入收货人'), trigger: "blur" },
  ];
  rules.value["address" + item] = [
    { required: true, message: t('tenantAddress.请输入详细地址'), trigger: "blur" },
  ];
});

// 当弹窗打开且有data数据时，加载现有数据进表单
watch(show, (val) => {
  if (val && props.data?.id) {
    // 编辑模式，加载数据
    formData.value = { ...props.data };
    formData.value.region = [
      props.data.provinceId,
      props.data.cityId,
      props.data.areaId,
    ];
  }
});

const formRef = ref();

const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        ...formData.value,
        // 如果是编辑模式，保留ID
        ...(props.data?.id ? { id: props.data.id } : {}),
        provinceId: formData.value.region[0],
        cityId: formData.value.region[1],
        areaId: formData.value.region[2],
      };
      const port = props.data?.id
        ? Api.updateTenantAddress
        : Api.addTenantAddress;
      port(submitData).then((res) => {
        if (res.status == 200) {
          ElMessage.success(t('tenantAddress.操作成功'));
          emit("success", submitData);
          close();
        }
      });
    }
  });
};

const close = () => {
  // 重置表单数据
  formData.value.id = undefined;
  formData.value.phone = "";
  formData.value.region = [];
  langs.forEach((item) => {
    formData.value["name" + item] = "";
    formData.value["address" + item] = "";
  });
  show.value = false;
  formRef.value.resetFields();
};
</script>

<style lang="scss" scoped>
// 可以添加特定的样式
</style>
